package com.itheima.reggie.service.impl;

import com.itheima.reggie.entity.ShoppingCart;
import com.itheima.reggie.mapper.ShoppingCartMapper;
import com.itheima.reggie.service.ShoppingCartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpSession;
import java.time.LocalDateTime;
import java.util.List;
@Service
public class ShoppingCartServiceImpl implements ShoppingCartService {
    @Autowired(required = false)
    private ShoppingCartMapper shoppingCartMapper;
    @Autowired(required = false)
    private HttpSession session;
    @Override
    public List<ShoppingCart> findAll(Long userId) {
        List<ShoppingCart> shoppingCarts = shoppingCartMapper.findAll(userId);
        return shoppingCarts;
    }

    @Override
    public Boolean add(ShoppingCart shoppingCart) {
        shoppingCart.setCreateTime(LocalDateTime.now());
        ShoppingCart byNameAndUserId = shoppingCartMapper.findByNameAndUserId(shoppingCart);
        if (byNameAndUserId==null){
            shoppingCart.setNumber(1);
            shoppingCartMapper.add(shoppingCart);
        }else{
            shoppingCart.setNumber(byNameAndUserId.getNumber()+1);
            shoppingCartMapper.updateNumber(shoppingCart);
        }



        return true;
    }

    @Override
    public Boolean deleteByIds(Long userId) {
        Integer integer = shoppingCartMapper.deleteByIds(userId);
        return integer>0;
    }

    @Override
    public ShoppingCart findByNameAndUserId(ShoppingCart shoppingCart) {
        ShoppingCart shoppingCart1 = shoppingCartMapper.findByNameAndUserId(shoppingCart);
        return shoppingCart1;
    }

    @Override
    public Boolean updateNumber(ShoppingCart shoppingCart) {
        Integer integer = shoppingCartMapper.updateNumber(shoppingCart);
        return integer>0;

    }

    @Override
    public Boolean deleteById(ShoppingCart shoppingCart) {
        Long user = (Long) session.getAttribute("user");
        shoppingCart.setUserId(user);
        ShoppingCart byNameAndUserId = shoppingCartMapper.findByNameAndUserId(shoppingCart);

        if (byNameAndUserId.getNumber()==1){
            shoppingCartMapper.deleteById(byNameAndUserId);
        }else if(byNameAndUserId.getNumber()>1){
            byNameAndUserId.setNumber(byNameAndUserId.getNumber()-1);
            shoppingCartMapper.updateNumber(byNameAndUserId);
        }
        return true;
    }
}
